package main.java.FSMDE.controllers;

import java.util.ArrayList;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

import main.java.ERMDE.models.Diagram;
import main.java.FSMDE.infrastructure.IProjectContext;
import main.java.FSMDE.models.ComplexComponent;
import main.java.FSMDE.models.Component;
import main.java.FSMDE.models.ComponentCollection;
import main.java.FSMDE.models.ComponentType;
import main.java.FSMDE.views.IComponentView;


public class ComponentController extends BaseController implements
		IComponentController {

	private IComponentView componentView;
	private ComponentCollection components;

	public ComponentController(IProjectContext projectContext,
			IComponentView componentView) {
		super(projectContext);
		this.components = new ComponentCollection();
		this.setComponentView(componentView);
	}

	@Override
	public Component addNewComponent(ComplexComponent componentFather) {
		String compName = componentView.getName();
		if (compName != null) {
			Component comp = Component.create(compName,
					componentView.getComponentType());
			if (comp.getType().equals(ComponentType.Generic))
				comp.setGenericType(componentView.getGenericTypeName());
			if (componentFather == null) {
				this.components.add(comp);
			} else {
				componentFather.getComponents().add(comp);
			}
			return comp;
		}
		return null;
	}

	@Override
	public ComponentCollection getComponents() {
		return components;
	}

	@Override
	public void setComponents(ComponentCollection components) {
		this.components = components;
	}

	@Override
	public IComponentView getComponentView() {
		return this.componentView;
	}

	@Override
	public void setComponentView(IComponentView componentView) {
		this.componentView = componentView;
		this.componentView.setController(this);
		this.componentView.setComponents(this.components);
	}

	@Override
	public void removeAttribute(Component component) {
		if (this.components.contains(component))
			this.components.remove(component);
	}

	@Override
	public boolean editComponent(Component componentSelected) {
		return false;
	}

	@Override
	public void deleteElement(TreePath treePath) {
		DefaultMutableTreeNode node = (DefaultMutableTreeNode) treePath
				.getLastPathComponent();
		this.components.remove(node.toString().substring(0,
				node.toString().indexOf(" : ")));
	}

	@Override
	public void setErmDiagrams(ArrayList<Diagram> ermDiagrams) {
		this.componentView.setErmDiagrams(ermDiagrams);
	}
}